/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.aternity.geolocations.draw;

import com.aternity.common.geolocation.CountryBoundariesRTree;
import com.aternity.common.geolocation.ReverseGeoCodingDataAccess;
import com.aternity.common.geolocation.TableauNamesCache;
import com.aternity.common.geom.Polygon2D;
import com.aternity.system.common.csv.CSVRWFactoryImpl;
import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collection;
import java.util.Set;

/**
 *
 * @author danielo
 */
public class SettingsFrame extends javax.swing.JFrame {
    
    DrawingPanel drawingPanel;
    TableauNamesCache namesCache;
    CountryBoundariesRTree rTree;
    
    ReverseGeoCodingDataAccess reverseGeoCodingDataAccess;
    
    private String selectedEntity;

    /**
     * Creates new form PolygonBrowser
     */
    public SettingsFrame(DrawingPanel drawingPanel) {
        this.drawingPanel = drawingPanel;
        initComponents();
        valuesCombo.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
        valuesCombo.getEditor().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                handleSelectedEntity();
            }
        });
        reverseGeoCodingDataAccess = new ReverseGeoCodingDataAccess(CSVRWFactoryImpl.getInstance());

        ReverseGeoCodingDataAccess dataLoader = getReverseGeoCodingDataLoader();

        namesCache = dataLoader.getNamesCache();
        rTree = dataLoader.getBoundariesRTree();
    }

    private ReverseGeoCodingDataAccess getReverseGeoCodingDataLoader() {
        final String aternityHome = System.getProperty("aternity.home");
        Path countryGeometryDataFile = FileSystems.getDefault().getPath(aternityHome, "geo_locations", "country.geom.csv");
        Path stateGeometryDataFile = FileSystems.getDefault().getPath(aternityHome, "geo_locations", "state.geom.csv");
        ReverseGeoCodingDataAccess dataLoader = new ReverseGeoCodingDataAccess(CSVRWFactoryImpl.getInstance());
        dataLoader.load(countryGeometryDataFile, stateGeometryDataFile);
        return dataLoader;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        fileCombo = new javax.swing.JComboBox();
        valuesCombo = new javax.swing.JComboBox();
        showReducedPolygonsCB = new javax.swing.JCheckBox();
        jLabel1 = new javax.swing.JLabel();
        toleranceTF = new javax.swing.JTextField();

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Browse Country/State"));

        fileCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "", "State", "Country" }));
        fileCombo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fileComboActionPerformed(evt);
            }
        });

        valuesCombo.setEditable(true);
        valuesCombo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                valuesComboActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(fileCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 58, Short.MAX_VALUE)
                .addComponent(valuesCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(31, 31, 31))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(fileCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(valuesCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(23, Short.MAX_VALUE))
        );

        showReducedPolygonsCB.setSelected(true);
        showReducedPolygonsCB.setText("Show Reduced Polygons");
        showReducedPolygonsCB.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                showReducedPolygonsCBItemStateChanged(evt);
            }
        });

        jLabel1.setText("Tolerance: ");

        toleranceTF.setText("1.0");
        toleranceTF.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                toleranceTFActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(showReducedPolygonsCB)
                        .addGap(68, 68, 68)
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(toleranceTF, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(170, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(26, 26, 26)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(showReducedPolygonsCB)
                    .addComponent(jLabel1)
                    .addComponent(toleranceTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(123, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void fileComboActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileComboActionPerformed
        JComboBox cb = (JComboBox) evt.getSource();
        String type = (String) cb.getSelectedItem();
        
        Set<String> values;
        if ("State".equals(type)) {
            values = namesCache.getAllStateNames();
        } else {
            values = namesCache.getAllCountryNames();
        }
        final String[] valuesArray = values.toArray(new String[values.size()]);
        Arrays.sort(valuesArray);
        valuesCombo.setModel(new DefaultComboBoxModel(valuesArray));
        AutoCompleteDecorator.decorate(this.valuesCombo);
    }//GEN-LAST:event_fileComboActionPerformed

    private void valuesComboActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_valuesComboActionPerformed
        handleSelectedEntity();
    }//GEN-LAST:event_valuesComboActionPerformed

    private void showReducedPolygonsCBItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_showReducedPolygonsCBItemStateChanged
        drawingPanel.setReducedPolygonsTolerance(Double.parseDouble(toleranceTF.getText()));
        drawingPanel.setShowReducedPolygons(showReducedPolygonsCB.isSelected());
    }//GEN-LAST:event_showReducedPolygonsCBItemStateChanged

    private void toleranceTFActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_toleranceTFActionPerformed
        drawingPanel.setReducedPolygonsTolerance(Double.parseDouble(toleranceTF.getText()));
        drawingPanel.refreshReducedPolygons();
    }//GEN-LAST:event_toleranceTFActionPerformed
    
    private boolean handleSelectedEntity() {
        String entityName = (String) valuesCombo.getSelectedItem();
        if (entityName.trim().isEmpty()) {
            return true;
        }
        if (entityName.equals(selectedEntity)) {
            return true;
        }
        selectedEntity = entityName;
        final Collection<Polygon2D> polygonData = reverseGeoCodingDataAccess.getPolygonCache().getPolygonData(entityName);
        System.out.println("Selected entity: " + entityName + "  |  " + polygonData.size());
        SettingsFrame.this.drawingPanel.setPolygonData(polygonData);
        return false;
    }
    
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(DrawPolygonFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(DrawPolygonFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(DrawPolygonFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(DrawPolygonFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                SettingsFrame f = new SettingsFrame(null);
                //f.setSize(1000, 800);
                f.setVisible(true);
            }
        });
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox fileCombo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JCheckBox showReducedPolygonsCB;
    private javax.swing.JTextField toleranceTF;
    private javax.swing.JComboBox valuesCombo;
    // End of variables declaration//GEN-END:variables
}
